<?php
class GalleryAction extends Action{
    
    public $action;
    public $module;
    public $moduleId;
    public $imageId;
    
    public function run(){
        $this->loginRequired();
        switch(strtolower($this->action)){
            case 'default':
                $this->defaultImage();
                break;
            case 'delete':
                $this->deleteImage();
                break;
        }//end switch
    }
    
    public function defaultImage(){
        Gallery::model()->setDefault($this->module, $this->moduleId, $this->imageId);
        if(Yii::app()->request->isAjaxRequest){
            echo CJSON::encode(array(
                'status' => 'success',
            ));
        }else
            $this->controller->redirect(Yii::app()->request->urlReferrer);
    }
    
    public function deleteImage(){
        if($this->moduleId){
            $model=Gallery::model()->module($this->module)->moduleId($this->moduleId)->findByPk((int)$this->imageId);
            if(empty($model)) HttpStatus::code(404);
            
            $model->scenario='delete';
            if($model->deleteRecord()){
                Gallery::model()->setDefault($this->module, $this->moduleId);
                if(Yii::app()->request->isAjaxRequest){
                    echo CJSON::encode(array(
                        'status' => 'success',
                    ));
                }else
                    $this->controller->redirect(Yii::app()->request->urlReferrer);
            }else{
                if(Yii::app()->request->isAjaxRequest){
                    echo CJSON::encode(array(
                        'status' => 'success',
                        'error' => $model->getErrors()
                    ));
                }
            }
        }
    }
}